// 用户状态管理
import { defineStore } from "pinia";
import type { UserInfo } from "@/types/user";
import { formatAuthorityCodeList } from "@/utils/permissionCalc";
import {
  usePermissionStore,
  filterAsyncRouter,
  formatRouterModuleOpenStatus,
} from "@/stores/permission";
import router from "@/router";

interface UserState {
  token: string | null;
  userInfo: UserInfo | null;
  permissions: string[];
  // 权限检查缓存：单点与任意集
  _permCache: Record<string, boolean>;
  _anyPermCache: Record<string, boolean>;
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    token: localStorage.getItem("token"),
    userInfo: JSON.parse(localStorage.getItem("userInfo") || "null"),
    permissions: JSON.parse(localStorage.getItem("permissions") || "[]"),
    _permCache: {},
    _anyPermCache: {},
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    isPlatformAdmin: (state) => state.userInfo?.role === "PLATFORM_ADMIN",
    isTenantAdmin: (state) => {
      const role = state.userInfo?.role;
      return role === "SUPER_ADMIN" || role === "SITE_ADMIN";
    },
    isTenantOperator: () => false,
  },

  actions: {
    // 设置 token
    setToken(token: string) {
      this.token = token;
      localStorage.setItem("token", token);
    },

    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
      localStorage.setItem("userInfo", JSON.stringify(userInfo));

      // 计算并保存权限列表（基于角色类型自动计算）
      this.calculateAndUpdatePermissions(userInfo);
    },

    // 登录
    login(token: string, userInfo: UserInfo) {
      this.setToken(token);
      this.setUserInfo(userInfo);
    },

    // 登出
    logout() {
      this.token = null;
      this.userInfo = null;
      this.permissions = [];
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("permissions");
      this.clearPermissionCache();
    },

    /**
     * 更新权限并清理缓存
     */
    updatePermissions(perms: string[]) {
      this.permissions = perms || [];
      localStorage.setItem("permissions", JSON.stringify(this.permissions));
      this.clearPermissionCache();
    },

    /**
     * 计算并更新用户权限（基于角色类型）
     */
    async calculateAndUpdatePermissions(userInfo: UserInfo) {
      try {
        const permissionStore = usePermissionStore();

        // 获取所有路由
        const allRoutes = router.getRoutes();

        // 调用权限计算工具计算权限码列表
        const authorityCodeList = formatAuthorityCodeList(allRoutes as any, {
          roles: userInfo.roles || [],
          authorityCodes: userInfo.authorityCodes || [],
          moduleResourceCodes: userInfo.moduleResourceCodes || [],
        });

        // 更新权限列表
        this.updatePermissions(authorityCodeList);

        // 过滤路由：先格式化模块状态，再根据权限过滤
        const formattedRoutes = formatRouterModuleOpenStatus(
          allRoutes as any,
          userInfo.moduleResourceCodes || []
        );

        const filteredRoutes = filterAsyncRouter(
          formattedRoutes,
          authorityCodeList,
          userInfo.moduleResourceCodes || []
        );

        // 更新应用路由
        await permissionStore.updateAppRouter(filteredRoutes);

        console.log("[权限系统] 权限计算完成", {
          roles: userInfo.roles,
          authorityCodeCount: authorityCodeList.length,
          filteredRoutesCount: filteredRoutes.length,
        });
      } catch (error) {
        console.error("[权限系统] 权限计算失败", error);
      }
    },

    /**
     * 清空权限检查缓存
     */
    clearPermissionCache() {
      this._permCache = {};
      this._anyPermCache = {};
    },

    // 检查权限
    hasPermission(permissionCode: string): boolean {
      // 平台管理员和租户超级管理员默认拥有所有权限
      const role = this.userInfo?.role;
      if (role === "PLATFORM_ADMIN" || role === "SUPER_ADMIN") {
        return true;
      }
      // 缓存命中
      const cached = this._permCache[permissionCode];
      if (typeof cached !== "undefined") return cached;
      // 其他角色（包括站点管理员）严格按权限码控制
      // 支持两种格式：原始权限码和 page_ 前缀格式
      let allowed = this.permissions.includes(permissionCode);
      if (!allowed && !permissionCode.startsWith("page_")) {
        // 如果原始权限码不存在，尝试检查 page_ 前缀格式
        allowed = this.permissions.includes(`page_${permissionCode}`);
      }
      this._permCache[permissionCode] = allowed;
      return allowed;
    },

    // 检查是否拥有任一权限
    hasAnyPermission(permissionCodes: string[]): boolean {
      const role = this.userInfo?.role;
      if (role === "PLATFORM_ADMIN" || role === "SUPER_ADMIN") {
        return true;
      }
      const key = (permissionCodes || []).slice().sort().join("|");
      const cached = this._anyPermCache[key];
      if (typeof cached !== "undefined") return cached;
      const allowed = permissionCodes.some((code) =>
        this.permissions.includes(code)
      );
      this._anyPermCache[key] = allowed;
      return allowed;
    },

    // 检查是否拥有所有权限
    hasAllPermissions(permissionCodes: string[]): boolean {
      const role = this.userInfo?.role;
      if (role === "PLATFORM_ADMIN" || role === "SUPER_ADMIN") {
        return true;
      }
      return permissionCodes.every((code) => this.permissions.includes(code));
    },
  },
});
